package com.ruoyi.syn;

/**
 * @Author syc
 * @Date Created in 8:58 2022/8/19
 * @Description 不安全的买票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket b1 = new BuyTicket();
        new Thread(b1,"我").start();
        new Thread(b1,"你").start();
        new Thread(b1,"黄牛").start();
    }


}

class BuyTicket implements Runnable {
    // 票
    private int ticketNums = 10;
    boolean flag = true; // 外部停止方式
    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //睡眠
        Thread.sleep(100);
        // 买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }


}


